package com.sc.search;

import cn.hutool.json.JSONUtil;
import com.sc.search.mapper.ApArticleMapper;
import com.sc.search.pojo.SearchArticleVo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
public class InitDocument {
    @Autowired
    private RestHighLevelClient client;


    @Autowired
    private ApArticleMapper apArticleMapper;

    @Test
    public void initDocument() throws Exception {
        List<SearchArticleVo> list = apArticleMapper.loadArticleList();
        BulkRequest request = new BulkRequest("article_info");
        list.forEach((article) -> {//遍历
            String json = JSONUtil.toJsonStr(article);
            IndexRequest index = new IndexRequest()
                    .id(article.getId().toString())
                    .source(json, XContentType.JSON);
            request.add(index);
        });
        client.bulk(request, RequestOptions.DEFAULT);
    }
}
